package action.util;

import com4j.excel.ClassFactory;
import com4j.excel._Application;

import constants.ExcelParams;

public class MacroUtil {

	public static boolean formatMacro(String file) {
		_Application app = createApplication(file);

		app.run(ExcelParams.FORMAT_MACRO, null, null, null, null, null, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null);

		app.getActiveWorkbook().save(0);
		app.quit();

		return true;
	}

	public static boolean filterMacro(String file, String column, String pattern) {
		if (column == null || pattern == null
				|| !column.matches(COLUMN_PATTERN) || pattern.length() == 0) {
			return false;
		}

		_Application app = createApplication(file);
		app.run(ExcelParams.FILTER_MACRO, column.toUpperCase(), pattern, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null);

		app.getActiveWorkbook().save(0);
		app.quit();

		return true;
	}

	public static boolean divideMacro(String file, String column, String outdir) {
		if (column == null || !column.matches(COLUMN_PATTERN)) {
			return false;
		}

		if (outdir == null) {
			outdir = ExcelParams.DEFAULT_OUTDIR;
		}

		if (!outdir.matches(DIRECTORY_PATTERN)) {
			outdir = outdir + "\\";
		}

		_Application app = createApplication(file);
		app.run(ExcelParams.DIVIDE_MACRO, column.toUpperCase(), outdir, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null);

		app.getActiveWorkbook().close(false, null, null, 0);
		app.quit();

		return true;
	}

	private static _Application createApplication(String file) {
		_Application app = ClassFactory.createApplication();

		app.setVisible(0, false);
		app.setDisplayAlerts(0, false);

		app.getWorkbooks().open(ExcelParams.MACRO_EXCEL, null, null, null,
				null, null, null, null, null, null, null, null, null, null,
				null, 0);

		app.getWorkbooks().open(file, null, null, null, null, null, null, null,
				null, null, null, null, null, null, null, 0);

		return app;
	}

	private static final String COLUMN_PATTERN = "^[a-zA-Z]{1,2}$";

	private static final String DIRECTORY_PATTERN = "^.+?[/\\\\]$";

}
